<template>
  <XenPageLayout
    title="新增调休申请"
    title-align="left"
    navbar-bg-color="#7881de"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    contentStyle="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;"
  >
    <!-- 表单内容区域 -->
    <view class="form-container">
      <XenDynamicFormCard
        title="填写调休申请信息"
        subtitle="请填写完整调休申请信息以便审批"
        :sections="formSections"
        :modelValue="formData"
        :errors="formErrors"
        :showFooter="false"
        @update:modelValue="handleFormDataChange"
        @fieldBlur="handleFieldBlur"
        @pickerChange="handlePickerChange"
        @datetimeChange="handleDateTimeChange"
        @imageUpload="handleImageUpload"
        @imageSuccess="handleImageSuccess"
        @imageFail="handleImageFail"
        @imageDelete="handleImageDelete"
        @fileUpload="handleFileUpload"
        @fileSuccess="handleFileSuccess"
        @fileFail="handleFileFail"
        @fileDelete="handleFileDelete"
        @departmentPickerChange="handleDepartmentPickerChange"
        @departmentPickerOpen="handleDepartmentPickerOpen"
        @departmentPickerClose="handleDepartmentPickerClose"
        @autoCompleteChange="handleAutoCompleteChange"
        @autoCompleteSearch="handleAutoCompleteSearch"
      >
        <!-- 加班记录内容插槽 -->
        <template #overtime-records-content="{ field }">
          <view v-if="formData.compOffType === '等时调休'">
            <AvailableOvertimeCard
              :overtime-list="availableOvertimeList"
              @update-comp-off-hours="handleUpdateCompOffHours"
            />
          </view>
          <view v-else class="no-overtime-tip">
            <text class="tip-text">请先选择"等时调休"类型</text>
          </view>
        </template>
      </XenDynamicFormCard>
    </view>

    <!-- 固定底部操作按钮 -->
    <XenFormActions
      :actions="formActions"
      :hidden="isDepartmentPickerOpen"
      @action="handleFormAction"
    />
  </XenPageLayout>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, watch } from "vue";
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenDynamicFormCard from "@/components/XenDynamicFormCard.vue";
import XenFormActions from "@/components/XenFormActions.vue";
import AvailableOvertimeCard from "./components/AvailableOvertimeCard.vue";
import { getFormSectionsByPageType } from "./form-config";
import { useCompOffInfo } from "./composables/useInfo";
// 导入统一事件系统
import { ResignInfoEvents } from "@/utils/eventBus";

// 获取新增页面的表单分组
const formSections = getFormSectionsByPageType("create");

// 部门选择器打开状态
const isDepartmentPickerOpen = ref<boolean>(false);

// 表单操作按钮配置
const formActions = computed(() => [
  {
    key: "cancel",
    label: "取消",
    type: "default" as const,
  },
  {
    key: "submit",
    label: "提交",
    type: "primary" as const,
  },
]);

// 使用调休申请信息 Composable
const {
  formData,
  formErrors,
  pickerValues,
  validateField,
  handlePickerChange,
  handleDateTimeChange,
  initializeOptions,
  createCompOff,
  search,
  getBillCode,
  calculateDays,
  availableOvertimeList,
  isLoadingOvertime,
  loadAvailableOvertimeList,
  updateOvertimeCompOffHours,
  autoFillCurrentUserEmployee,
} = useCompOffInfo();

// 表单数据变化处理
const handleFormDataChange = (newData: Record<string, any>) => {
  Object.assign(formData, newData);
};

// 字段失焦处理
const handleFieldBlur = (fieldKey: string) => {
  validateField(fieldKey);
};

// 部门选择器变化处理
const handleDepartmentPickerChange = (
  fieldKey: string,
  value: string,
  _item: any,
) => {
  // XenDynamicFormCard组件会同时触发 @update:model-value 和 @change 事件
  // @update:model-value 已经通过 handleFormDataChange 设置了 formData[fieldKey] = value (部门ID)
  // 这里我们只需要保存部门ID到pickerValues中，用于提交到后端

  // 确保formData中存储的是部门ID（用于组件正确显示选中状态）
  formData[fieldKey] = value;

  // 同时保存到pickerValues中（用于提交到后端）
  pickerValues[fieldKey] = value;

  // 触发验证
  validateField(fieldKey);
};

// 部门选择器弹框打开处理
const handleDepartmentPickerOpen = () => {
  isDepartmentPickerOpen.value = true;
};

// 部门选择器弹框关闭处理
const handleDepartmentPickerClose = () => {
  isDepartmentPickerOpen.value = false;
};

// 自动补全变化处理
const handleAutoCompleteChange = (
  fieldKey: string,
  _value: string,
  option: any,
) => {
  // 对于自动补全，formData中存储显示文本，pickerValues中存储实际值
  if (option) {
    formData[fieldKey] = option.text;
    pickerValues[fieldKey] = option.value;

    // 如果是员工选择，自动填入员工工号、姓名、公司和部门信息
    if (fieldKey === "personId" && option.subtitle) {
      // 从subtitle中提取工号，格式为 "工号: 12345 | 部门名称"
      const staffNoMatch = option.subtitle.match(/工号:\s*(\S+)/);
      if (staffNoMatch) {
        formData.staffNo = staffNoMatch[1];
      }
      // 员工姓名就是选中的文本
      formData.name = option.text;

      // 如果有扩展数据，自动填入公司和部门信息
      if (option.extData) {
        // 更新表单数据
        formData.orgName = option.extData.orgName || "";
        formData.groupName = option.extData.groupName || "";

        // 更新选择器值
        pickerValues.orgId = option.extData.orgId || "";
        pickerValues.groupId = option.extData.groupId || "";

        // 同步到表单数据中的隐藏字段
        formData.orgId = option.extData.orgId || "";
        formData.groupId = option.extData.groupId || "";
      }
    }
  } else {
    formData[fieldKey] = "";
    pickerValues[fieldKey] = "";

    // 如果清空员工选择，也清空员工工号、姓名、公司和部门信息
    if (fieldKey === "personId") {
      formData.staffNo = "";
      formData.name = "";
      formData.orgName = "";
      formData.groupName = "";
      formData.orgId = "";
      formData.groupId = "";
      pickerValues.orgId = "";
      pickerValues.groupId = "";
    }
  }

  // 触发验证
  validateField(fieldKey);
};

// 自动补全搜索处理
const handleAutoCompleteSearch = async (fieldKey: string, query: string) => {
  // 搜索逻辑已经在组件内部通过searchApi处理
};

// 处理加班记录已调休时长更新
const handleUpdateCompOffHours = (overtimeId: string, hours: number) => {
  updateOvertimeCompOffHours(overtimeId, hours);
};

// 监听开始时间和结束时间变化，自动计算天数
watch(
  [() => formData.startTime, () => formData.endTime],
  ([startTime, endTime]) => {
    if (startTime && endTime) {
      formData.days = calculateDays(startTime, endTime);
    } else {
      formData.days = "";
    }
  },
);

// 监听调休类型和员工变化，加载可用加班记录
watch(
  [() => formData.compOffType, () => pickerValues.personId, () => formData.staffNo],
  ([compOffType, personId, staffNo]) => {
    if (compOffType === '等时调休' && (personId || staffNo)) {
      const personIdOrStaffNo = personId || staffNo;
      if (personIdOrStaffNo) {
        loadAvailableOvertimeList(personIdOrStaffNo);
      }
    } else {
      availableOvertimeList.value = [];
    }
  },
);

// 页面加载时获取数据
onMounted(async () => {
  // 初始化选项数据
  await initializeOptions();

  // 获取单据编号
  const billCode = await getBillCode();
  if (billCode) {
    formData.billCode = billCode;
  }

  // 自动填充当前用户的员工信息
  try {
    const success = await autoFillCurrentUserEmployee();
    if (success) {
      console.log("已自动填充当前用户员工信息");
    } else {
      console.log("未能自动填充当前用户员工信息，请手动选择");
    }
  } catch (error) {
    console.error("自动填充员工信息时发生错误:", error);
  }
});

// 图片上传处理
const handleImageUpload = async (field: any, event: any) => {
  // 图片上传逻辑
  console.log("图片上传:", field.key, event);
};

const handleImageSuccess = (_field: any, _event: any) => {
  // 图片上传成功处理
};

const handleImageFail = (_field: any, _event: any) => {
  // 图片上传失败处理
};

const handleImageDelete = (field: any, event: any) => {
  // 图片删除逻辑
  console.log("图片删除:", field.key, event);
};

// 文件上传处理
const handleFileUpload = async (_field: any, _event: any) => {
  // 文件上传逻辑
};

const handleFileSuccess = (_field: any, _event: any) => {
  // 文件上传成功处理
};

const handleFileFail = (_field: any, _event: any) => {
  // 文件上传失败处理
};

const handleFileDelete = (_field: any, _event: any) => {
  // 文件删除处理
};

// 表单操作处理
const handleFormAction = (action: any) => {
  switch (action.key) {
    case "cancel":
      handleCancel();
      break;
    case "submit":
      handleSubmit();
      break;
    default:
      console.log("未知操作:", action.key);
  }
};

// 取消按钮
const handleCancel = () => {
  uni.navigateBack();
};

// 提交表单
const handleSubmit = async () => {
  uni.showLoading({ title: "提交中..." });

  // 使用Composable中的创建方法（两步提交流程）
  const response = await createCompOff();

  uni.hideLoading();

  if (response.success && response.data && response.data.ID) {
    // 重新调用search接口获取最新的完整列表数据
    const searchResponse = await search({});
    if (searchResponse && searchResponse.length > 0) {
      // 发送完整列表数据更新事件
      ResignInfoEvents.emit("refresh", {
        id: response.data.ID,
        data: searchResponse,
        customAction: "add",
      });
    }

    uni.showToast({
      title: "提交成功",
      icon: "success",
      success: () => {
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      },
    });
  } else {
    // 处理不同类型的错误信息
    let errorMessage = "提交失败，请重试";

    if (response.error) {
      // 显示具体的业务错误信息
      errorMessage = response.error;
    } else if (response.validation?.firstErrorMessage) {
      // 显示表单验证错误信息
      errorMessage = response.validation.firstErrorMessage;
    }

    uni.showToast({
      title: errorMessage,
      icon: "none",
      duration: 3000, // 延长显示时间，让用户能看清错误信息
    });
  }
};
</script>

<style lang="scss" scoped>
.form-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  // 为固定底部按钮预留空间：按钮44px + 上下padding32px + 边框1px + 缓冲15px + 安全区域
  padding-bottom: calc(92px + constant(safe-area-inset-bottom));
  padding-bottom: calc(92px + env(safe-area-inset-bottom));
}

.no-overtime-tip {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  text-align: center;
  
  .tip-text {
    color: #999;
    font-size: 14px;
  }
}
</style>
